package com.ww.wwaiagent.app;

import com.ww.wwaiagent.advisor.MyLoggerAdvisor;
//import com.ww.wwaiagent.chatmemory.DatabaseChatMemory;
import com.ww.wwaiagent.chatmemory.FileBasedChatMemory;
import com.ww.wwaiagent.chatmemory.MySQLBasedChatMemory;
import com.ww.wwaiagent.rag.JobAppRagCustomAdvisorFactory;
import com.ww.wwaiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @author 15357
 * @create 2025/5/12 14:28
 */
@Component
@Slf4j
public class JobApp {

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "你是一个面试官，请根据候选人的回答进行面试。";

    /**
     * 初始化AI ChatClient
     * @param dashscopeChatModel 阿里大模型
     * @author wangwang
     * @date 2025/5/12
     */
    public JobApp(ChatModel dashscopeChatModel, MySQLBasedChatMemory chatMemory) {
        // 初始化基于文件的对话记忆
//        String fileDir = System.getProperty("user.dir") + "/tmp/chatMemory";
//        ChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        // 初始化基于数据库的对话记忆
//        ChatMemory chatMemory = new MySQLBasedChatMemory();
//        // 初始化基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        // 自定义日志 Advisor，可按需开启
                        new MyLoggerAdvisor()
                        // 自定义推理增强 Advisor，可按需开启
//                        , new ReReadingAdvisor()
                )
                .build();
    }

    /**
     * AI 基础对话（支持多轮对话记忆）
     * @param message 用户消息
     * @param chatId 聊天室id
     * @author wangwang
     * @date 2025/5/12
     */
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     * AI 基础对话（支持多轮对话记忆，SSE 流式传输）
     * @param message
     * @param chatId
     * @author wangwang
     * @date 2025/6/4
     */
    public Flux<String> doChatByStream(String message, String chatId) {
        Flux<String> content = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
        return content;
    }

    record JobReport(String title, List<String> suggestions) {

    }

    /**
     * AI 辅助报告（实战结构化输出）
     * @param message 用户消息
     * @param chatId 聊天室id
     * @author wangwang
     * @date 2025/5/12
     */
    public JobReport doChatWithReport(String message, String chatId) {
        JobReport jobReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成辅助报告结果，标题为{用户名}的辅助报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(JobReport.class);
        log.info("jobReport: {}", jobReport);
        return jobReport;
    }

    @Resource
    private VectorStore jobAppVectorStore;
    @Resource
    private Advisor jobAppRagCloudAdvisor;
    @Resource
    private VectorStore pgVectorVectorStore;

    @Resource
    private QueryRewriter queryRewriter;

    public String doChatWithRag(String message, String chatId) {
        // 查询重写
        String rewrittenMessage = queryRewriter.doQueryRewrite(message);

        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                // 使用改写后的查询
//                .user(rewrittenMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                // 应用 RAG 检索增强服务（基于云知识库服务）
//                .advisors(jobAppRagCloudAdvisor)
                // 应用知识库问答
                .advisors(new QuestionAnswerAdvisor(jobAppVectorStore))
                // 应用 RAG 检索增强服务（基于 PgVector 向量存储）
//                .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                // 应用自定义的 RAG 检索增强服务（围挡内查询器 + 上下文增强）
//                .advisors(JobAppRagCustomAdvisorFactory.createJobAppRagCustomAdvisor(
//                        jobAppVectorStore, "在职"
//                ))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    @Resource
    private ToolCallback[] allTools;

    /**
     * AI 求职报告功能（支持调用工具）
     * @param message
     * @param chatId
     * @author wangwang
     * @date 2025/6/4
     */
    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


}
